﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.CodeMarkers.Contracts;

namespace Microsoft.CodeMarkers.Internal
{
    class CodeMarkerClientHost : CodeMarkerBaseHost
    {
        public CodeMarkerClient Client { get; private set; }
        ICodeMarkerService Service { get; set; }
        IChannelFactory Factory { get; set; }

        public CodeMarkerClientHost(int targetProcessId)
            : base(targetProcessId)
        {
            this.Client = new CodeMarkerClient();
            InstanceContext c = new InstanceContext(this.Client);
            EndpointAddress address = new EndpointAddress(this.ServiceUri);
            DuplexChannelFactory<ICodeMarkerService> factory = new DuplexChannelFactory<ICodeMarkerService>(c, new NetNamedPipeBinding(), address);

            this.Service = factory.CreateChannel();
            this.Service.RegisterClient(this.ServiceUri.AbsolutePath);
            this.Factory = factory;
        }

        public override void Dispose()
        {
            IChannel channel = this.Service as IChannel;

            if (channel.State < CommunicationState.Closing)
            {
                this.Service.ReleaseClient(this.ServiceUri.AbsolutePath);
                this.Factory.Close();
            }
        }
    }
}
